#include "crypto/types.h"
#include "crypto/json.h"
#include "crypto/parse/json/ParseJsonImp.h"
#include "crypto/des.h"
#include "crypto/des.h"
#include "crypto/md5.h"
#include "tls/common.h"

int TCPResponse(enum TCP_RESPONSE_CODE code, byte *desKey, byte *buffer)
{
    byte buffer2[2048];
    Json *json = JsonInit();
    int len;
    JsonValue *jsonValue = JsonValueInit(JSON_VALUE_TYPE_LONG);
    jsonValue->value = malloc(sizeof(uint64));
    *(uint64 *)(jsonValue->value) = code;
    JsonPut(json, JsonItemInit("code", jsonValue));
    JsonString(json, buffer2);
    JsonFree(json);
    len = strlen(buffer2);
    des(buffer2, buffer, desKey, len, ENCODE);
    len = (len + 7) / 8 * 8;
    MD5_value *md5Value = md5sum(buffer, len);
    memcpy(buffer + len, md5Value, 16);
    free(md5Value);
    len += 16;
    return len;
}

int TCPSend(byte *data, int len, byte *desKey, byte *buffer)
{
    des(data, buffer, desKey, len, ENCODE);
    // des encode data len
    len = (len + 7) / 8 * 8;
    MD5_value *md5Value = md5sum(buffer, len);

    // *(uint *)(buffer + len) = md5Value->value[0];
    // *(uint *)(buffer + len + 4) = md5Value->value[1];
    // *(uint *)(buffer + len + 8) = md5Value->value[2];
    // *(uint *)(buffer + len + 12) = md5Value->value[3];

    memcpy(buffer + len, md5Value, 16);
    free(md5Value);
    len += 16;
    return len;
}

// already check the md5 number
Json *TCPReceive(byte *data, int len, byte *desKey)
{
    byte buffer[2048];
    des(data, buffer, desKey, len, DECODE);
    buffer[len] = 0;
    return JsonParse(buffer);
}